package 代码随想录.数组.有序数组的平方;

/**lc977. 有序数组的平方
 * link:https://leetcode-cn.com/problems/squares-of-a-sorted-array/
 * @author ChenweiLin
 * @create 2021-11-29 21:21
 */
public class squaresOfaSortedArray {
    public static void main(String[] args) {
        int[] ints = sortedSquares(new int[]{-4, -1, 0, 3, 10});
        for (int anInt : ints) {
            System.out.println(anInt);
        }
    }

    public static int[] sortedSquares(int[] nums) {
        //前后指针
        int h = 0;//head
        int t = nums.length-1;//tail
        int[] result  = new int[nums.length];
        int index = nums.length-1;//新数组的下标，我们从result的最后一位开始放数字

        while(h <= t){//指针相遇跳出循环
            if(nums[h]*nums[h] >= nums[t]*nums[t])
                result[index--] = nums[h]*nums[h++];//index往前移，h往后移动
            else result[index--] = nums[t]*nums[t--];//index往前移，t往后移
        }

        return result;
    }

}
